package com.filter;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        String requestURI=req.getRequestURI();
        String contextPath=req.getContextPath();

        if((!requestURI.equals(contextPath+"/"))  && (!requestURI.contains("login.jsp"))){
            HttpSession session=req.getSession();
            if(session.getAttribute("admin")==null){  //证明用户没登录
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>window.top.location.href='"+contextPath+"/login.jsp?loginflag=0'</script>");
            }
            else{
                filterChain.doFilter(request, response);
            }
        }
        else{
            filterChain.doFilter(request, response);
        }
    }

    @Override
    public void destroy() {

    }
}
